﻿using System;
using System.Net;
using System.ComponentModel;
using System.Collections.Generic;
using System.Collections;
using System.Linq;
using System.Diagnostics;
using Fdd.Aspen.Client.ViewModel.Infrastructure;

namespace Fdd.Aspen.Client.ViewModels
{
    public abstract class BaseViewModel : INotifyPropertyChanged, INotifyDataErrorInfo
    {
        public event PropertyChangedEventHandler PropertyChanged;
        public event EventHandler<DataErrorsChangedEventArgs> ErrorsChanged;
        
        private ViewModelException _exception;
        private bool _showError;
        private bool _isBusy = false;

        private Dictionary<string, List<ValidationErrorInfo>> _errors = new Dictionary<string, List<ValidationErrorInfo>>();


        protected virtual void RemoveErrorFromPropertyAndNotifyErrorChanges(
                                                                string propertyName, 
                                                                int errorCode)
        {
            ValidateProperty(propertyName);

            if (_errors.ContainsKey(propertyName))
            {
                RemoveErrorFromPropertyIfErrorCodeAlreadyExist(propertyName, errorCode);
                NotifyErrorsChanged(propertyName);
            }

        }


        protected virtual void AddErrorToPropertyAndNotifyErrorChanges(
                                                                string propertyName,
                                                                ValidationErrorInfo errorInfo)
        {
            ValidateProperty(propertyName);

            if (errorInfo == null)
                throw new ArgumentNullException("errorInfo");

            RemoveErrorFromPropertyIfErrorCodeAlreadyExist(propertyName, errorInfo.ErrorCode);

            if (!_errors.ContainsKey(propertyName))
                _errors.Add(propertyName, new List<ValidationErrorInfo>());

            _errors[propertyName].Add(errorInfo);

            NotifyErrorsChanged(propertyName);
        }


        private void RemoveErrorFromPropertyIfErrorCodeAlreadyExist(string propertyName, int errorCode)
        {
            if (_errors.ContainsKey(propertyName))
            {
                var errorToRemove = _errors[propertyName].SingleOrDefault(
                                            error => error.ErrorCode == errorCode);

                if (errorToRemove != null)
                {
                    _errors[propertyName].Remove(errorToRemove);
                    
                    if (_errors[propertyName].Count == 0)
                        _errors.Remove(propertyName);
                }
            }
        }


        public IEnumerable GetErrors(string propertyName)
        {
            if (!_errors.ContainsKey(propertyName))
                return _errors.Values;

            return _errors[propertyName];
        }

        
        public bool HasErrors
        {
            get { return (this._errors.Count > 0 || Exception != null); }
        }


        public bool ShowError
        {
            get { return _showError; }
            set
            {
                _showError = value;
                NotifyPropertyChanged("ShowError");
            }
        }


        public ViewModelException Exception
        {
            get { return _exception; }
            set
            {
                _exception = value;
                NotifyPropertyChanged("Exception");
            }
        }


        public bool IsBusy
        {
            get { return _isBusy; }
            protected set
            {
                _isBusy = value;
                NotifyPropertyChanged("IsBusy");
            }
        }


        protected virtual void NotifyErrorsChanged(string propertyName)
        {
            ValidateProperty(propertyName);

            if (ErrorsChanged != null)
                ErrorsChanged(this, new DataErrorsChangedEventArgs(propertyName));
        }


        protected virtual void NotifyPropertyChanged(string propertyName)
        {
            ValidateProperty(propertyName);

            if (PropertyChanged != null)
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }

        
        protected virtual void ShowException(Exception exception)
        {
            Exception = new ViewModelException("", exception.Message);
            ShowError = true;
        }


        [Conditional("DEBUG")]
        [DebuggerStepThrough]
        private void ValidateProperty(string propertyName)
        {
            if (this.GetType().GetProperty(propertyName) == null)
                throw new MissingMemberException(propertyName);
        }
    }
}
